# -*- coding:utf-8 -*-
"""
@Time : 2022/4/27 5:24 PM
@Author: binkuolo
@Des: 用户管理
"""
from datetime import date
import os
import time
from core.Response import success, fail
from core.Utils import random_str
from core.Auth import check_permissions
from fastapi import Request, Query, APIRouter, Security, File, UploadFile
from config import settings
from typing import List
from tortoise.queryset import F

router = APIRouter(prefix='')

@router.post("/picture", dependencies=[Security(check_permissions)], summary="图片上传")
async def picture_upload(req: Request, file: UploadFile = File(...)):
    """
    图片上传
    :param req:
    :param picture:
    :return:
    """
    # 文件存储路径
    path = f"{settings.STATIC_DIR}/upload/" + date.today().strftime("%Y%m%d")
    start = time.time()
    filename = random_str() + '.' + file.filename.split(".")[1]
    try:
        if not os.path.isdir(path):
            os.makedirs(path, 0o777)
        res = await file.read()
        with open(f"{path}/{filename}", "wb") as f:
            f.write(res)
        data = {
            'time': time.time() - start,
            'url': f"https://www.xmabc.net/apifiles/upload/"+ date.today().strftime("%Y%m%d") +f"/{filename}"}
        return success(msg="上传成功", data=data)
    except Exception as e:
        print("上传失败:", e)
        return fail(msg=f"图片上传失败!")